package icedot.library.common.base;


import android.Manifest;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;


import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class BaseActivity extends FragmentActivity
{
	private static final int PERMISSON_REQUESTCODE = 0;

	protected String[] needPermissions = {
			Manifest.permission.WRITE_EXTERNAL_STORAGE,
			Manifest.permission.READ_EXTERNAL_STORAGE,
			Manifest.permission.ACCESS_FINE_LOCATION,
			Manifest.permission.ACCESS_COARSE_LOCATION,
	};

	protected BaseApplication 	_baseApp;
	protected boolean 			_active;

    protected String _uuid;

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		_uuid = UUID.randomUUID().toString();
		Logger.showDebugMsg("UUID",_uuid);

		_baseApp = (BaseApplication) getApplication();
		_baseApp.addActivity(this);
		Logger.showDebugMsg(this.getClass().getSimpleName(),"onCreate");
	}
	
	@Override
	protected void onDestroy() 
	{
		super.onDestroy();
		_baseApp.popActivity(this);
		Logger.showDebugMsg(this.getClass().getSimpleName(),"onDestory");
	}

	@Override
	protected void onStop() 
	{
		super.onStop();
		Logger.showDebugMsg(this.getClass().getSimpleName(),"onStop");
	}
	
	@Override
	protected void onStart() 
	{
		super.onStart();
		Logger.showDebugMsg(this.getClass().getSimpleName(),"onStart");
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		_active = true;
		Logger.showDebugMsg(this.getClass().getSimpleName(),"onResume");
	}
	
	@Override
	protected void onPause()
	{
		super.onPause();
		_active = false;
		Logger.showDebugMsg(this.getClass().getSimpleName(),"onPause");
	}
	
	/**
	 * 模拟一个点击事件 打开软键盘
	 * @param primaryTextField
	 */
	public void setKeyboardFocus(final EditText primaryTextField) 
	{
        (new Handler()).postDelayed(new Runnable()
        {
            public void run() 
            {
                primaryTextField.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
                                MotionEvent.ACTION_DOWN, 0, 0, 0));
                primaryTextField.dispatchTouchEvent(MotionEvent.obtain(
                                SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
                                MotionEvent.ACTION_UP, 0, 0, 0));
            }
        }, 100);
	}
	/**
	 * 如果软键盘打开,则隐藏软键盘
	 */
	public void hideKeyboard()
	{
		if(this.getCurrentFocus() == null)
		{
			InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
			boolean isOpen=imm.isActive();//isOpen若返回true，则表示输入法打开
			if(isOpen)
			{
				imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}
		else
		{
			((InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE)).
			hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
					InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

    public String getUuid()
    {
        return _uuid;
    }

	public void keywordLight(String str,String keywords,int color,TextView view)
	{
		SpannableString sp = new SpannableString(str); 
		 Pattern p = Pattern.compile(keywords);
		 Matcher m = p.matcher(str);  
		 
		 while(m.find())
		 {
			 int start = m.start();
			 int end = m.end();
			 sp.setSpan(new ForegroundColorSpan(color), start ,end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		 }
		 view.setText(sp);
	}
	
	/**
	 * 在onResume调用该方法,黑屏后,在打开不需要输入密码就可以看到该界面
	 * @param act
	 */
	public void openLock(BaseActivity act)
	{
		final Window win = act.getWindow();
		final WindowManager.LayoutParams params = win.getAttributes();
		params.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
	}
	
//	public MessageDlgFragment showOneBtnDlg(String title,String content)
//	{
//		MessageDlgFragment dlg = new MessageDlgFragment();
//		dlg.setTitle(title);
//		dlg.setContent(content);
//		dlg.setCancelBtnVisiable(View.GONE);
//		dlg.setSetBtnVisiable(View.GONE);
//		dlg.show(this);
//		return dlg;
//	}
	
	/**
	 * 检查app是否运行
	 * @param context
	 * @param packageName
	 * @return
	 */
	public static boolean isAppRunning(Context context,String packageName)
	{
//		String packageName = this.getPackageName();
//		String topActivityClassName=getTopActivityName();
//		
//		Log.d(this.getClass().getSimpleName(),packageName + ":" +topActivityClassName);
//		if (packageName != null && topActivityClassName != null && 
//				packageName.equals(topActivityClassName)) 
//		{
//
//			return true;
//		} 
//		else 
//		{
//			return false;
//		}
		if(context == null)
			 return false;
		ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
	    List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
	    for (RunningAppProcessInfo appProcess : appProcesses) 
	    {
	         if (appProcess.processName.equals(packageName)) 
	         {
	                if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND)
	                {
	                          Log.i("后台", appProcess.processName);
	                          return true;
	                }
	                else
	                {
	                          Log.i("前台", appProcess.processName);
	                          return false;
	                }
	           }
	    }
	    return false;
	}
	
	/**
	 * 检查服务是否运行
	 * @param context
	 * @param className
	 * @return
	 */
	 public static boolean isServiceRunning(Context context,String className) 
	 {
		 if(context == null)
			 return false;
         boolean isRunning = false;
         ActivityManager activityManager = (ActivityManager)
        		 context.getSystemService(Context.ACTIVITY_SERVICE); 
         List<ActivityManager.RunningServiceInfo> serviceList 
         = activityManager.getRunningServices(100);
        if (serviceList.size() == 0) 
        {
             return false;
        }
        for (int i=0; i<serviceList.size(); i++) 
        {
             if (serviceList.get(i).service.getClassName().equals(className) == true) 
             {
                 isRunning = true;
                 break;
             }
        }
        return isRunning;
     }
	
	public static String getTopActivityName(Context context)
	{
		 if(context == null)
			 return "";
		String topName = "";
		ActivityManager activityManager =
				(ActivityManager)(context.getSystemService(android.content.Context.ACTIVITY_SERVICE )) ;
		 List<RunningTaskInfo> runningTaskInfos = activityManager.getRunningTasks(1) ;
		 for(RunningTaskInfo info : runningTaskInfos)
		 {
			 Log.d("Activity Task List", info.topActivity.getPackageName());
		 }
		 if(runningTaskInfos != null)
		 {
	    	 ComponentName f = runningTaskInfos.get(0).topActivity;
	    	 topName = f.getPackageName();	    	
	     }
		 
		 return topName;
	}

	protected void checkPermissions(String... permissions)
	{
		List<String> needRequestPermissonList = findDeniedPermissions(permissions);
		if(null != needRequestPermissonList
				&& needRequestPermissonList.size() > 0)
		{
			ActivityCompat.requestPermissions(this,
					needRequestPermissonList.toArray(
							new String[needRequestPermissonList.size()]),
					PERMISSON_REQUESTCODE);
		}
	}
	/**
	 * 获取权限集中需要申请权限的列表
	 *
	 * @param permissions
	 * @return
	 * @since 2.5.0
	 */
	private List<String> findDeniedPermissions(String[] permissions)
	{
		List<String> needRequestPermissonList = new ArrayList<String>();
		for (String perm : permissions)
		{
			if(ContextCompat.checkSelfPermission(this,
					perm) != PackageManager.PERMISSION_GRANTED
					|| ActivityCompat.shouldShowRequestPermissionRationale(
					this, perm))
			{
				needRequestPermissonList.add(perm);
			}
		}
		return needRequestPermissonList;
	}

	/**
	 * 检测是否说有的权限都已经授权
	 *
	 * @param grantResults
	 * @return
	 * @since 2.5.0
	 */
	private boolean verifyPermissions(int[] grantResults)
	{
		for (int result : grantResults)
		{
			if(result != PackageManager.PERMISSION_GRANTED)
			{
				return false;
			}
		}
		return true;
	}

	@Override
	public void onRequestPermissionsResult(int requestCode,
										   String[] permissions, int[] paramArrayOfInt)
	{
		if(requestCode == PERMISSON_REQUESTCODE)
		{
			if(!verifyPermissions(paramArrayOfInt))
			{
				showMissingPermissionDialog();
			}
		}
	}

	/**
	 * 显示提示信息
	 *
	 * @since 2.5.0
	 */
	private void showMissingPermissionDialog()
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("提示");
		builder.setMessage("当前应用缺少必要权限。\n\n请点击\"设置\"-\"权限\"-打开所需权限。");

		// 拒绝, 退出应用
		builder.setNegativeButton("取消",
				new DialogInterface.OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						finish();
					}
				});

		builder.setPositiveButton("设置",
				new DialogInterface.OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						startAppSettings();
					}
				});

		builder.setCancelable(false);

		builder.show();
	}

	private void startAppSettings()
	{
		Intent intent = new Intent(
				Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
		intent.setData(Uri.parse("package:" + getPackageName()));
		startActivity(intent);
	}

	public void needUpdate()
	{

	}

	public void needUpdate(int flag,Object obj)
	{

	}
}
